/*
 * Copyright (C) 2011 Jake Wharton
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pricy.me;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Currency;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.internal.SessionTracker;
import com.facebook.internal.Utility;
import com.facebook.model.GraphUser;
import com.pricy.me.model.User;

//We're the same! Manifest and content text changes only.
public class MainActivity extends Activity {
	private Button mFacebookBtn;
	private Button mInscriptionBtn;
	private ProgressDialog mProgress;
	private SessionTracker mSessionTracker;
	private Session mCurrentSession;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        if(readFile("user.info").contains("id")){
        	this.finish();
//        	final Intent swipeList = new Intent(this, MyProductsActivity.class);
//        	startActivity(swipeList);
        	final Intent stream = new Intent(MainActivity.this, StreamProductsActivity.class);
        	startActivity(stream);
        }
        	
        setTheme(R.style.Theme_Sherlock_Light);
        setContentView(R.layout.login);
        
        mFacebookBtn	= (Button) findViewById(R.id.cb_facebook);
        mInscriptionBtn	= (Button) findViewById(R.id.inscription);
        
        mProgress		= new ProgressDialog(this);
        
        mFacebookBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				signInWithFacebook();
				signInWithFacebook();
			}
		});
        
        mInscriptionBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				InscriptionDialog dialog = new InscriptionDialog(MainActivity.this);
				dialog.show();
				
			}
		});
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        
        if (mCurrentSession.isOpened()) {
            Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {

                  // callback after Graph API response with user object
                  @Override
                  public void onCompleted(GraphUser userFb, Response response) {
                	  saveUserData(userFb);
                	  Log.e("FACEBOOK", "Result");
                  }
                });
            }
    }
    
    private void signInWithFacebook() {
    	
  		 
        mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() {

            @Override
            public void call(Session session, SessionState state, Exception exception) {
            }
        }, null, false);

        String applicationId = Utility.getMetadataApplicationId(getBaseContext());
        mCurrentSession = mSessionTracker.getSession();

        if (mCurrentSession == null || mCurrentSession.getState().isClosed()) {
            mSessionTracker.setSession(null);
            Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build();
            Session.setActiveSession(session);
            mCurrentSession = session;
        }

        if (!mCurrentSession.isOpened()) {
            Session.OpenRequest openRequest = null;
            openRequest = new Session.OpenRequest(MainActivity.this);

            if (openRequest != null) {
                openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
                openRequest.setPermissions(Arrays.asList("email", "user_location"));
                openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);

                mCurrentSession.openForRead(openRequest);
            }
        }else {
            Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
                  @Override
                  public void onCompleted(GraphUser userFb, Response response) {
                	saveUserData(userFb);
                	Log.e("FACEBOOK", "Complete");
                  }
                });
        }
    }
    
    private void saveUserData(GraphUser userFb) {
    	// start Facebook Login
    	 Log.e("FACEBOOK", "on save");
    	 mProgress.setMessage("Inscription & connexion ...");
  		 mProgress.show();
  		 
        Session.openActiveSession(this, true, new Session.StatusCallback() {

          // callback when session changes state
          @Override
          public void call(Session session, SessionState state, Exception exception) {
            if (session.isOpened()) {

              // make request to the /me API
              Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                // callback after Graph API response with user object
                @Override
                public void onCompleted(GraphUser userFb, Response response) {
                  if (userFb != null) {
                	 
              		
              		final User user = new User();
                	user.setUsername(userFb.getId());
  		        	user.setFacebook_id(Integer.parseInt(userFb.getId()));
  		        	user.setFirst_name(userFb.getFirstName());
  		        	user.setLast_name(userFb.getLastName());
  		        	user.setEmail(userFb.getProperty("email").toString());
  		        	if(userFb.getProperty("bio") != null) user.setAbout(userFb.getProperty("bio").toString());
  		        	if(userFb.getLocation() != null)user.setAdress(userFb.getLocation().getProperty("name").toString());
  		        	Currency currency = Currency.getInstance(Locale.getDefault());
  		        	user.setCurrency(currency.getCurrencyCode());
  		        	user.setPicture(getString(R.string.liengraphefacebook)+userFb.getId()+"/picture");
  		        	Log.e("FACEBOOK", user.toJSON());
  		        	
              		new Thread() {
              			@Override
              			public void run() {
              		        String name = "";
              		        int what = 1;
              		        
              		        try {
              		        	
              		        	// Create a new HttpClient and Post Header
              		            HttpClient httpclient = new DefaultHttpClient();
              		    	  final String urluser=getString(R.string.lien)+"api/user/new?json=";
                    			
              		            HttpPost httppost = new HttpPost(urluser+URLEncoder.encode(user.toJSON(), "UTF-8"));

              			            try {
              	
              			                // Execute HTTP Post Request
              			                HttpResponse response = httpclient.execute(httppost);
              			                String content = EntityUtils.toString(response.getEntity());
              			                Log.e("HTTP", content);
              			                // Write to file
              			                writeFile("user.info", content);
              			                
              			                MainActivity.this.finish();
              			            	final Intent category = new Intent(MainActivity.this, CategoryChoiceActivity.class);
              			            	startActivity(category);
              			            	
              			            } catch (ClientProtocolException e) {
              			                // TODO Auto-generated catch block
              			            } catch (IOException e) {
              			                // TODO Auto-generated catch block
              			            }
              		        	what = 0;
              		        } catch (Exception ex) {
              		        	Log.e("FACEBOOK",ex.toString());
              		        }
              		        
              		        mFbHandler.sendMessage(mFbHandler.obtainMessage(what, name));
              			}
              		}.start();
                    
                  }
                }
              });
            }
          }
        });
	}
    
    
	private Handler mFbHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			
			if (msg.what == 0) {
				String username = (String) msg.obj;
		        username = (username.equals("")) ? "No Name" : username;
		            
		        //SessionStore.saveName(username, MainActivity.this);
		        
		        mFacebookBtn.setText("  Facebook (" + username + ")");
		         
		        Toast.makeText(MainActivity.this, "Inscription réussie", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(MainActivity.this, "Inscription réussie", Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			
			if (msg.what == 1) {
				Toast.makeText(MainActivity.this, "Facebook logout failed", Toast.LENGTH_SHORT).show();
			} else {
	        	mFacebookBtn.setText("  Facebook (Not connected)");
	        	mFacebookBtn.setTextColor(Color.GRAY);
	        	   
				Toast.makeText(MainActivity.this, "Disconnected from Facebook", Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	private void writeFile(String file, String text){
		FileOutputStream fos;
		try {
			fos = getApplicationContext().openFileOutput(file, Context.MODE_PRIVATE);
			fos.write(text.getBytes());
        	fos.close();
		} catch (FileNotFoundException e) {
			Toast.makeText(getApplicationContext(), "ERROR: can't open file", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			Toast.makeText(getApplicationContext(), "ERROR: can't write file", Toast.LENGTH_SHORT).show();
		}	
	}
	private String readFile(String file) {
		StringBuilder json = new StringBuilder();
		try {
			FileInputStream fis = getApplicationContext().openFileInput(file);
			BufferedReader r = new BufferedReader(new InputStreamReader(fis));
			String line;
			while ((line = r.readLine()) != null) {
			    json.append(line);
			}
			fis.close();
			return json.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "0";
		} catch (IOException e) {
			e.printStackTrace();
			return "0";
		}
	}
    
}